package com.techblor.wechat.library.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.imageio.ImageIO;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClientUtil工具类
 *
 * @author zhangceven
 */
@Slf4j
public class HttpClientUtil {

    /**
     * 执行请求
     *
     * @param request
     * @param clazz
     * @return
     */
    public static <T> T executor(HttpUriRequest request, Class<T> clazz) {
        String result = null;
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = client.execute(request);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (IOException e) {
            log.error("执行调用接口异常: {}", e.getMessage());
        } finally {
            close(response);
        }

        if (StringUtil.isBlank(result)) {
            return null;
        }

        return JSON.parseObject(result, clazz);
    }

    /**
     * 发送get请求
     *
     * @param url   请求地址
     * @param param 请求参数
     * @return
     */
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        String result = "";
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient client = getCloseableSSLHttpClient();
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }

            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = client.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }

        } catch (Exception e) {
            log.error("执行调用接口异常: {}", e.getMessage());
        } finally {
            close(response);
        }

        return getResult(result);
    }

    /**
     * 发送get请求
     *
     * @param url 请求地址
     * @return
     */
    public static String doGet(String url) {
        return doGet(url, null);
    }

    /**
     * 发送post请求
     *
     * @param url   请求地址
     * @param param 请求参数
     * @return
     */
    public static String doPost(String url, Map<String, String> param) {
        String result = "";
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient client = getCloseableSSLHttpClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }

                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            // 执行http请求
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            log.error("执行调用接口异常: {}", e.getMessage());
        } finally {
            close(response);
        }

        return getResult(result);
    }

    /**
     * 发送post请求
     *
     * @param url
     * @return
     */
    public static String doPost(String url) {
        return doPost(url, null);
    }

    /**
     * 以json方式发送post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, String json) {
        CloseableHttpResponse response = null;
        String result = "";
        try {
            CloseableHttpClient client = getCloseableSSLHttpClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            log.error("执行调用接口异常: {}", e.getMessage());
        } finally {
            close(response);
        }

        return getResult(result);
    }

    public static BufferedImage sendPostJson(String url, String json){
        CloseableHttpResponse response = null;
        String result = "";
        try {
            CloseableHttpClient client = getCloseableSSLHttpClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                return ImageIO.read(new ByteArrayInputStream(bytes));
            }
        } catch (Exception e) {
            log.error("执行调用接口异常: {}", e.getMessage());
        } finally {
            close(response);
        }

        return null;
    }

    /**
     * 关闭响应
     *
     * @param response
     */
    private static void close(CloseableHttpResponse response) {
        try {
            if (response != null) {
                response.close();
            }

        } catch (IOException e) {
            log.error("执行关闭资源异常: {}", e.getMessage());
        }
    }

    /**
     * 获取可自动关闭的请求SSL http客户端
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    private static CloseableHttpClient getCloseableSSLHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();
        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);
        //创建自定义的httpclient对象
        return HttpClients.custom().setConnectionManager(connManager).build();
    }

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                                           String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[]{trustManager}, null);
        return sslContext;
    }


    private static String getResult(String result) {
        if (StringUtil.isBlank(result)) {
            return null;
        }

        return result;
    }
}
